package cn.wolfcode.wolf2w.interceptor;

import cn.wolfcode.wolf2w.annotation.RequireLogain;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import com.sun.javafx.media.PrismMediaFrameHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckLoginInterceptor implements HandlerInterceptor{
    @Autowired
    private IUserInfoRedisService userInfoRedisService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //首先排除OPTIONS请求
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        //检测映射方法中是否有自定义注解
        //强转
        HandlerMethod handlerMethod= (HandlerMethod) handler;
        //判断,方法是否有注解,如果没有,则放行
        if (!(handlerMethod.hasMethodAnnotation(RequireLogain.class))){
            return true;
        }
        //有,从redis中拿取登录对象
        //从头拿token数据
        String token = request.getHeader("token");
        //组装key
        UserInfo userInfo = userInfoRedisService.checkUser(token);
        //如果userInfo有值,说明已经登录,放行
        if (userInfo!=null){
            return true;
        }
        //没有值,则未登录,resp返回未登录的jsonresult
        response.setContentType("application/json; charset=utf-8");
        JsonResult jsonResult = JsonResult.noLogin();
        response.getWriter().write(JSON.toJSONString(jsonResult));
        return false;
    }
}
